package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Role;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AdminWorkUnsafeThreadControllerServlet", urlPatterns = "/Admin/AdminWorkUnsafeThreadControllerServlet")
public class AdminWorkUnsafeThreadControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -3076663364283146494L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		int boardId = Integer.parseInt(request.getParameter("boardid"));
		int threadId = Integer.parseInt(request.getParameter("threadid"));
		String userId = request.getUserPrincipal().getName();

		try {

			User user = User.get(userId);
			Role role = user.getRole();

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			if (role == Role.SiteAdmin || user.isBoardAdmin(boardId)) {
				Thread.makeWorkUnsafe(boardId, threadId);
			}

			response.sendRedirect(request.getContextPath() + "/NewAnswersControllerServlet?boardid=" + boardId);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}

	}

}
